<?php
namespace app\module\controllers;

use app\controllers\NewsController;
use app\models\AdRecorder;
use app\models\BlockRecorder;
use app\models\CateRecorder;
use app\models\GoodsRecorder;
use app\models\MemberRecorder;
use app\models\NewscateRecorder;
use app\models\NewsRecorder;
use app\models\OrderRecorder;
use yii\web\Controller;
use function PHPUnit\Framework\StaticAnalysis\HappyPath\AssertNull\consume;

class IndexController extends BaseController {
    public $enableCsrfValidation = false;

    //获取首页显示分类
    public function actionIndexcatelist(){
        $list = CateRecorder::find()->select(['id','thumb_pic','cate_name'])->where('is_index=1')->orderBy('cate_order DESC')->asArray()->all();
        foreach($list as $k=>$v){
            $list[$k]['thumb_pic'] = str_replace("../",\Yii::$app->params['pic_url'],$v['thumb_pic']);
        }
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result);
    }

    //获取首页关于我们
    //id:模板id
    //格式：{param:{id:0}}
    public function actionIndexus(){
        $post = \Yii::$app->request->post('param');
        $id = intval($post['id']);
        $result = $this->get_block($id);
        return json_encode($result);
    }

    //获取商品列表
    //参数：num-数量，type=1-最新，2-推荐，3-热门,0-全部;rand:0-否，1-随机
    //格式：{param:{num:5,type:1}}
    public function actionNewlist(){
        $post = \Yii::$app->request->post('param');
        $num = intval($post['num']);
        $type = intval($post['type']);
        $rand = intval($post['rand']);
        $list = GoodsRecorder::find()->select(['id','goods_name','goods_type','thumb_pic','goods_cate','goods_price','addtime'])->where('is_down=0');
        if($type){
            $list = $list->andWhere(['like','goods_type','"'.$type.'"']);
        }
        if($rand){
            $list = $list->orderBy('RAND()');
        }else{
            $list = $list->orderBy('addtime DESC');
        }
        $list=$list->limit($num)->asArray()->all();
        foreach($list as $k=>$v){
            $list[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            $list[$k]['thumb_pic'] = str_replace('../',\Yii::$app->params['pic_url'],$v['thumb_pic']);
        }
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result);
    }

    //分页获取商品
    //参数：page-当前页,key-关键字,type-类型,0-不限,1-最新，2-推荐，3-热门;cate_id-分类id;time:0-不限，1-从高到底，2-从低到高
    //格式：{page:{page:1,key:'关键字',type:0,cate_id:0,time:0}}
    public function actionGoodslist(){
        $post = \Yii::$app->request->post('page');
        $page = intval($post['page'])-1;
        $pagesize = \Yii::$app->params['pagesize'];
        $offset = $page*$pagesize;
        $cate_id = intval($post['cate_id']);
        $child_cate = $this->get_child_cate($cate_id);
        $child_cate[]=$cate_id;
        $time = intval($post['time']);
        $list = GoodsRecorder::find()->select(['id','goods_name','goods_type','thumb_pic','goods_cate','goods_price','addtime'])->where('is_down=0');
        if($cate_id){
            $list = $list->andWhere(['in','goods_cate',$child_cate]);
        }
        switch($time){
            case 0:
                $list = $list->orderBy('addtime DESC');
                break;
            case 1:
                $list = $list->orderBy('addtime ASC');
                break;
            case 2:
                $list = $list->orderBy('addtime DESC');
                break;
        }
        $list = $list->limit($pagesize)->offset($offset)->asArray()->all();
        foreach($list as $k=>$v){
            $list[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            $list[$k]['thumb_pic'] = str_replace('../',\Yii::$app->params['pic_url'],$v['thumb_pic']);
        }
        if(count($list)){
            $result = ['result'=>1,'data'=>$list];
        }else{
            $result = ['result'=>0,'data'=>'没有内容了'];
        }

        return json_encode($result);
    }

    //获取下级分类
    //参数：parent,对应的父级分类
    //格式：{param:{parent:0}}
    public function actionChildcatelist(){
        $post = \Yii::$app->request->post('param');
        $parent = intval($post['parent']);
        $list = CateRecorder::find()->select(['id','cate_name','thumb_pic'])->where('parent_id=:id',[':id' => $parent])->asArray()->all();
        foreach($list as $k=>$v){
            $list[$k]['thumb_pic'] = str_replace("../",\Yii::$app->params['pic_url'],$v['thumb_pic']);
        }
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result);
    }

    //获取产品信息
    //参数：id-商品id
    //格式:{id:0}
    public function actionContent(){
        $id = \Yii::$app->request->post('id');
        $model = GoodsRecorder::find()->select(['id','goods_name','goods_pics','goods_content','hits','goods_cate','goods_price'])->where('id=:id',[':id' => $id])->andWhere('is_down=0')->asArray()->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容'];
            return json_encode($result);
        }
        $model['goods_pics'] = json_decode($model['goods_pics'],true);
        $arr=[];
        foreach($model['goods_pics'] as $v){
            $arr[] = str_replace('../',\Yii::$app->params['pic_url'],$v);
        }
        $model['goods_pics'] = $arr;
        $cate = CateRecorder::find()->where('id='.$model['goods_cate'])->one();
        $model['goods_cate'] = $cate->cate_name;
        $model['goods_content'] = str_replace("<img",'<img style="height:100%;width:100%;"',$model['goods_content']);
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result);
    }

    //登录
    public function actionLogin(){
        $code  = \Yii::$app->request->post('code');
        $appid = \Yii::$app->params['appid'];
        $secret = \Yii::$app->params['secret'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $res = file_get_contents($url);
        $res = json_decode($res,true);
        $openid = $res['openid'];
        if(empty($openid)){
            $result = ['result'=>0,'data'=>'请使用微信登陆'];
            return json_encode($result);
        }
        $model = MemberRecorder::find()->where('openid=:openid',[':openid' => $openid])->one();
        if(!$model){
            $model = new MemberRecorder();
            $model->addtime = time();
            $model->openid = $openid;
            $model->token = \Yii::$app->security->generateRandomString();
            $model->save(false);
        }
        $result = ['result'=>1,'data'=>$model->token];
        return json_encode($result);
    }

    //获取订单
    public function actionOrder(){
        $post = \Yii::$app->request->post();
        $token = $post['OrderRecorder']['token'];
        $user = MemberRecorder::find()->where('token=:token',[':token' => $token])->one();
        if(!$user){
            $result = ['result'=>2,'data'=>'不存在相关会员，请重新登陆'];
            return json_encode($result);
        }
        $model = new OrderRecorder();
        $model->addtime = time();
        $model->user_id = $user->id;
        $result = $model->add($post);
        return json_encode($result);

    }

    //获取所有分类
    public function actionAllcate(){
        $arr = $this->get_cate_list();
        $result = ['result'=>1,'data'=>$arr];
        return json_encode($result);
    }

    //获取资讯分类
    public function actionNewscatelist(){
        $list = NewscateRecorder::find()->select(['id','cate_name','thumb_pic'])->orderBy('cate_order ASC')->asArray()->all();
        foreach($list as $k=>$v){
            $list[$k]['thumb_pic'] = str_replace('../',\Yii::$app->params['pic_url'],$v['thumb_pic']);
        }
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result);
    }

    //获取列表
    public function actionNewslist(){
        $post = \Yii::$app->request->post('page');
        $page = intval($post['page'])-1;
        $pagesize = \Yii::$app->params['pagesize'];
        $offset = $page*$pagesize;
        $cate_id = intval($post['cate_id']);
        $list = NewsRecorder::find()->select(['id','title','cate_id','content','thumb_pic','addtime']);
        if($cate_id){
            $list = $list->andWhere('cate_id=:cate_id',[':cate_id' => $cate_id]);
        }
        $list = $list->limit($pagesize)->offset($offset)->orderBy('addtime DESC')->asArray()->all();
        foreach($list as $k=>$v){
            $list[$k]['thumb_pic'] = str_replace("../",\Yii::$app->params['pic_url'],$v['thumb_pic']);
            $list[$k]['time'] = date('Y-m-d',$v['addtime']);
        }
        if(count($list)){
            $result = ['result'=>1,'data'=>$list];
        }else{
            $result = ['result'=>0,'data'=>'没有内容了'];
        }

        return json_encode($result);
    }

    //获取资讯内容
    public function actionNewscontent(){
        $id = \Yii::$app->request->post('id');
        $model = NewsRecorder::find()->select(['id','title','content','cate_id','content','thumb_pic','addtime'])->where('id=:id',[':id' => $id])
        ->asArray()->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $cate = NewscateRecorder::find()->where('id='.$model['cate_id'])->one();
        $model['cate_name'] = empty($cate)?"未知":$cate->cate_name;
        $model['time']  = date('Y-m-d',$model['addtime']);
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result);
    }

    //获取地址和电话
    public function actionUsinfo(){
        $arr=[];
        $arr['tel'] = \Yii::$app->params['c_tel'];
        $arr['address'] = \Yii::$app->params['c_address'];
        $result = ['result'=>1,'data'=>$arr];
        return json_encode($result);
    }

    //获取轮播图
    public function actionFlash(){
        $list = AdRecorder::find()->select(['id','title','thumb_pic'])->orderBy('ad_order DESC')->asArray()->all();
        foreach($list as $k=>$v){
            $list[$k]['thumb_pic'] = empty($v['thumb_pic'])?"":str_replace("../",\Yii::$app->params['pic_url'],$v['thumb_pic']);
        }
        $result = ['result'=>1,"data"=>$list];
        return json_encode($result);
    }

    //获取名称
    public function actionWebname(){
        $result = ['result'=>1,'data'=>\Yii::$app->params['web_name']];
        return json_encode($result);
    }

    //点击
    public function actionHits(){
        $id = \Yii::$app->request->post('id');
        $model = GoodsRecorder::find()->where('id=:id',[':id' => $id])->one();
        if($model){
            $model->hits++;
            $model->save(false);
        }
    }



}